using System;
using System.IO;
using System.Net;
using System.Text;

namespace PlurkApi
{
    public class WebUtil
    {
        /// <summary>
        /// Make a http POST or GET request
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="methhod"></param>
        /// <param name="cookie">Get or set the cookie used in the request or response</param>
        /// <param name="waitContent">If you don't want wait the http content. Set this false, to get only the cookie for example.</param>
        /// <returns>Request response. If "" a error ocurred or you set the waitContent with false</returns>
        public string GetPage(String url, String methhod, ref Cookie cookie, Boolean waitContent)
        {
            HttpWebResponse response = null;

            try
            {
                var request = (HttpWebRequest) WebRequest.Create(url);
                request.Proxy = WebRequest.DefaultWebProxy;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 GTB5 (.NET CLR 3.5.30729)";
                request.CookieContainer = new CookieContainer();

                if (cookie != null)
                {
                    request.CookieContainer.Add(cookie);
                }

                request.Method = (string.IsNullOrEmpty(methhod) || string.Compare(methhod, "get", true) == 0)
                                     ? WebRequestMethods.Http.Get
                                     : WebRequestMethods.Http.Post;
                request.ContentLength = 0;

                //received data
                response = (HttpWebResponse) request.GetResponse();
                //get cookie
                try
                {
                    cookie = request.CookieContainer.GetCookies(request.RequestUri)[0];
                }
                catch
                {
                    cookie = null;
                }
                if (waitContent)
                {
                    var responseStream = response.GetResponseStream();
                    var reader = new StreamReader(responseStream, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return string.Empty;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
    }
}